using System;
using System.Windows;
using System.Windows.Input;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Windows.Controls;
using System.Windows.Media.Effects;
using System.Windows.Media;

namespace XmWinKit.Components
{
    public class WindowSkin : Window 
    {
        /// <summary>
        /// 调整窗口大小的边框检测范围（像素）
        /// </summary>
        private const int RESIZE_BORDER = 8;

        /// <summary>
        /// 窗口阴影的边距（像素）
        /// </summary>
        private const int SHADOW_MARGIN = 10;

        /// <summary>
        /// 标识窗口是否正在调整大小
        /// </summary>
        private bool _isResizing = false;

        /// <summary>
        /// 当前窗口调整方向
        /// </summary>
        private ResizeDirection _resizeDirection;

        /// <summary>
        /// 是否启用窗口拖拽移动功能
        /// </summary>
        private bool _isDragMove = true;

        /// <summary>
        /// 指定的可拖拽组件，为null时整个窗口都可拖拽
        /// </summary>
        private FrameworkElement _dragComponent = null;

        /// <summary>
        /// 窗口的主边框控件
        /// </summary>
        private Border _windowBorder;

        /// <summary>
        /// Windows消息：获取窗口最小最大信息
        /// </summary>
        private const int WM_GETMINMAXINFO = 0x0024;

        /// <summary>
        /// Windows消息：窗口位置改变
        /// </summary>
        private const int WM_WINDOWPOSCHANGING = 0x0046;

        /// <summary>
        /// 标识窗口是否处于水平方向贴边状态
        /// </summary>
        private bool _isWindowSnapped = false;

        /// <summary>
        /// 窗口阴影效果
        /// </summary>
        private DropShadowEffect _shadowEffect;

        /// <summary>
        /// 标识窗口是否处于垂直方向贴边状态
        /// </summary>
        private bool _isVerticallySnapped = false;

        /// <summary>
        /// 标识窗口是否处于全屏状态
        /// </summary>
        private bool _isFullScreen = false;
        
        /// <summary>
        /// 保存窗口在正常状态下的位置和大小
        /// </summary>
        private Rect _previousWindowRect = Rect.Empty;

        #region Windows Hit Test Constants
        /// <summary>
        /// Windows消息：命中测试
        /// </summary>
        private const int WM_NCHITTEST = 0x0084;

        /// <summary>
        /// 命中测试返回值：左边框
        /// </summary>
        private const int HTLEFT = 10;

        /// <summary>
        /// 命中测试返回值：右边框
        /// </summary>
        private const int HTRIGHT = 11;

        /// <summary>
        /// 命中测试返回值：顶部边框
        /// </summary>
        private const int HTTOP = 12;

        /// <summary>
        /// 命中测试返回值：左上角
        /// </summary>
        private const int HTTOPLEFT = 13;

        /// <summary>
        /// 命中测试返回值：右上角
        /// </summary>
        private const int HTTOPRIGHT = 14;

        /// <summary>
        /// 命中测试返回值：底部边框
        /// </summary>
        private const int HTBOTTOM = 15;

        /// <summary>
        /// 命中测试返回值：左下角
        /// </summary>
        private const int HTBOTTOMLEFT = 16;

        /// <summary>
        /// 命中测试返回值：右下角
        /// </summary>
        private const int HTBOTTOMRIGHT = 17;
        #endregion

        /// <summary>
        /// 窗口最小宽度（像素）
        /// </summary>
        private double _minWidth = 0;

        /// <summary>
        /// 窗口最小高度（像素）
        /// </summary>
        private double _minHeight = 0;

        /// <summary>
        /// 获取或设置窗口的最小宽度
        /// </summary>
        public new double MinWidth
        {
            get => _minWidth;
            set
            {
                if (value >= 0)
                {
                    _minWidth = value;
                    // 考虑阴影边距
                    base.MinWidth = value > 0 ? value + SHADOW_MARGIN * 2 : 0;
                }
            }
        }

        /// <summary>
        /// 获取或设置窗口的最小高度
        /// </summary>
        public new double MinHeight
        {
            get => _minHeight;
            set
            {
                if (value >= 0)
                {
                    _minHeight = value;
                    // 考虑阴影边距
                    base.MinHeight = value > 0 ? value + SHADOW_MARGIN * 2 : 0;
                }
            }
        }

        private double _backgroundOpacity = 1.0;

        /// <summary>
        /// 获取或设置窗口背景的透明度（0.0 - 1.0）
        /// </summary>
        public double BackgroundOpacity
        {
            get => _backgroundOpacity;
            set
            {
                if (value < 0.0 || value > 1.0)
                    throw new ArgumentOutOfRangeException(nameof(value), "透明度必须在 0.0 到 1.0 之间");
                
                _backgroundOpacity = value;
                UpdateBackgroundOpacity();
            }
        }

        /// <summary>
        /// 阴影效果颜色
        /// </summary>
        private Color _effectColor = Colors.Black;

        /// <summary>
        /// EffectColor 依赖属性
        /// </summary>
        public static readonly DependencyProperty EffectColorProperty =
            DependencyProperty.Register(
                "EffectColor",
                typeof(Color),
                typeof(WindowSkin),
                new PropertyMetadata(Colors.Black, OnEffectColorChanged));

        /// <summary>
        /// 获取或设置窗口阴影效果的颜色
        /// </summary>
        public Color EffectColor
        {
            get => _effectColor;
            set
            {
                _effectColor = value;
                UpdateShadowEffect();
            }
        }

        /// <summary>
        /// EffectColor属性改变时的回调
        /// </summary>
        private static void OnEffectColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is WindowSkin skin)
            {
                skin._effectColor = (Color)e.NewValue;
                skin.UpdateShadowEffect();
            }
        }

        /// <summary>
        /// 更新阴影效果
        /// </summary>
        private void UpdateShadowEffect()
        {
            if (_shadowEffect != null)
            {
                _shadowEffect.Color = _effectColor;
            }
        }

        public WindowSkin()
        {
            WindowStyle = WindowStyle.None;
            AllowsTransparency = true;
            Background = Brushes.Transparent;
            
            // 不在基类中设置具体的最小尺寸
            // 让具体的窗口类自己设置合适的最小尺寸
            
            MouseMove += OnWindowMouseMove;
            MouseDown += OnWindowMouseDown;
            MouseUp += OnWindowMouseUp;
            Loaded += OnWindowLoaded;
            SizeChanged += OnWindowSizeChanged;

            // 添加消息钩子
            SourceInitialized += (s, e) =>
            {
                IntPtr handle = new WindowInteropHelper(this).Handle;
                HwndSource.FromHwnd(handle)?.AddHook(WndProc);
            };

            // 加载默认样式
            Style = (Style)FindResource(typeof(WindowSkin));

            // 添加背景透明度初始化
            Loaded += (s, e) =>
            {
                UpdateBackgroundOpacity();
            };
        }

        static WindowSkin()
        {
            // 注册默认样式
            DefaultStyleKeyProperty.OverrideMetadata(
                typeof(WindowSkin), 
                new FrameworkPropertyMetadata(typeof(WindowSkin))
            );
        }

        // 新增属性
        public bool IsDragMove
        {
            get => _isDragMove;
            set => _isDragMove = value;
        }

        // 新增方法：设置可拖拽组件
        public void SetDragComponent(FrameworkElement component)
        {
            _dragComponent = component;
        }

        private void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            _windowBorder = GetTemplateChild("WindowBorder") as Border;
            if (_windowBorder != null)
            {
                // 创建新的阴影效果实例
                _shadowEffect = new DropShadowEffect
                {
                    BlurRadius = 10,
                    ShadowDepth = 0,
                    Opacity = 0.3,
                    Color = EffectColor  // 使用EffectColor属性
                };
                _windowBorder.Effect = _shadowEffect;
            }
            UpdateWindowMargin();
        }

        private void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
        {
            UpdateWindowMargin();
        }

        private void UpdateWindowMargin()
        {
            if (_windowBorder == null) return;

            bool isMaximized = WindowState == WindowState.Maximized;
            
            if (isMaximized)
            {
                // 最大化时移除所有边距
                _windowBorder.Margin = new Thickness(0);
                if (_shadowEffect != null)
                {
                    _shadowEffect.Opacity = 0;
                }
            }
            else
            {
                // 确保窗口大小不小于最小尺寸加上边距
                double minRequiredWidth = MinWidth + SHADOW_MARGIN * 2;
                double minRequiredHeight = MinHeight + SHADOW_MARGIN * 2;

                // 如果当前尺寸小于所需最小尺寸，强制设置 Border 的尺寸
                if (ActualWidth < minRequiredWidth || ActualHeight < minRequiredHeight)
                {
                    _windowBorder.Width = Math.Max(ActualWidth - SHADOW_MARGIN * 2, MinWidth);
                    _windowBorder.Height = Math.Max(ActualHeight - SHADOW_MARGIN * 2, MinHeight);
                }
                else
                {
                    _windowBorder.Width = double.NaN; // 重置为自动
                    _windowBorder.Height = double.NaN; // 重置为自动
                }

                // 根据贴边状态设置不同的边距
                double topMargin = _isVerticallySnapped ? 0 : SHADOW_MARGIN;
                double bottomMargin = _isVerticallySnapped ? 0 : SHADOW_MARGIN;
                double leftMargin = _isWindowSnapped ? 0 : SHADOW_MARGIN;
                double rightMargin = _isWindowSnapped ? 0 : SHADOW_MARGIN;

                _windowBorder.Margin = new Thickness(leftMargin, topMargin, rightMargin, bottomMargin);
                
                if (_shadowEffect != null)
                {
                    _shadowEffect.Opacity = 0.3;
                    
                    // 可选：如果想让阴影效果也只在有margin的地方显示，可以调整BlurRadius
                    _shadowEffect.BlurRadius = 10;
                    
                    if (_isVerticallySnapped)
                    {
                        // 当垂直贴边时，减小垂直方向的模糊半径
                        _shadowEffect.Direction = 0; // 确保阴影方向为水平
                    }
                    else if (_isWindowSnapped)
                    {
                        // 当水平贴边时，减小水平方向的模糊半径
                        _shadowEffect.Direction = 90; // 确保阴影方向为垂直
                    }
                    else
                    {
                        // 正常状态，全方向阴影
                        _shadowEffect.Direction = 0;
                    }
                }
            }
        }

        private void OnWindowMouseMove(object sender, MouseEventArgs e)
        {
            if (_isResizing) return;

            // 只在允许改变大小时才更新光标
            if (ResizeMode == ResizeMode.CanResize)
            {
                Point position = e.GetPosition(this);
                UpdateCursor(position);
            }
            else
            {
                Cursor = Cursors.Arrow;
            }
        }

        /// <summary>
        /// 根据鼠标位置更新光标样式
        /// </summary>
        /// <param name="position">相对于窗口的鼠标位置</param>
        /// <remarks>
        /// 根据鼠标在窗口边缘的位置显示不同的调整光标：
        /// - 左上/右下角：显示 ↖↘ 光标
        /// - 右上/左下角：显示 ↗↙ 光标
        /// - 左/右边缘：显示 ↔ 光标
        /// - 上/下边缘：显示 ↕ 光标
        /// - 其他区域：显示默认箭头光标
        /// 计算时会考虑窗口阴影的边距
        /// </remarks>
        private void UpdateCursor(Point position)
        {
            // 考虑阴影边距，计算鼠标是否在调整区域内
            bool left = position.X <= SHADOW_MARGIN + RESIZE_BORDER;     // 左边缘
            bool right = position.X >= ActualWidth - SHADOW_MARGIN - RESIZE_BORDER;   // 右边缘
            bool top = position.Y <= SHADOW_MARGIN + RESIZE_BORDER;      // 上边缘
            bool bottom = position.Y >= ActualHeight - SHADOW_MARGIN - RESIZE_BORDER; // 下边缘

            // 根据鼠标位置设置相应的光标样式
            if (left && top) Cursor = Cursors.SizeNWSE;        // 左上角
            else if (right && top) Cursor = Cursors.SizeNESW;  // 右上角
            else if (right && bottom) Cursor = Cursors.SizeNWSE; // 右下角
            else if (left && bottom) Cursor = Cursors.SizeNESW;  // 左下角
            else if (left) Cursor = Cursors.SizeWE;    // 左边缘
            else if (right) Cursor = Cursors.SizeWE;   // 右边缘
            else if (top) Cursor = Cursors.SizeNS;     // 上边缘
            else if (bottom) Cursor = Cursors.SizeNS;  // 下边缘
            else Cursor = Cursors.Arrow;               // 非调整区域
        }

        /// <summary>
        /// 处理窗口消息的回调函数
        /// </summary>
        /// <param name="hwnd">窗口句柄</param>
        /// <param name="msg">消息ID</param>
        /// <param name="wParam">消息的第一个参数</param>
        /// <param name="lParam">消息的第二个参数</param>
        /// <param name="handled">消息是否已处理</param>
        /// <returns>消息处理结果</returns>
        /// <remarks>
        /// 处理以下Windows消息：
        /// - WM_WINDOWPOSCHANGING (0x0046)：窗口位置改变时更新贴边状态
        /// - WM_NCHITTEST (0x0084)：处理窗口大小调整的鼠标命中测试
        /// - WM_GETMINMAXINFO (0x0024)：控制窗口的最小尺寸
        /// - WM_EXITSIZEMOVE (0x0232)：结束窗口大小调整或移动操作
        /// </remarks>
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case WM_WINDOWPOSCHANGING:
                    // 窗口位置改变时更新贴边状态
                    WINDOWPOS pos = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));
                    _isWindowSnapped = IsWindowSnapped(pos);
                    UpdateWindowMargin();
                    break;

                case WM_NCHITTEST:
                    // 如果禁用了改变大小功能，不处理命中测试
                    if (ResizeMode != ResizeMode.CanResize)
                    {
                        break;
                    }

                    // 将屏幕坐标转换为客户区坐标
                    // lParam 低16位为X坐标，高16位为Y坐标
                    Point point = PointFromScreen(new Point(
                        (int)(lParam.ToInt64() & 0xFFFF),
                        (int)(lParam.ToInt64() >> 16 & 0xFFFF)
                    ));

                    // 检测鼠标是否在窗口边框调整区域内
                    bool left = point.X <= SHADOW_MARGIN + RESIZE_BORDER;
                    bool right = point.X >= ActualWidth - SHADOW_MARGIN - RESIZE_BORDER;
                    bool top = point.Y <= SHADOW_MARGIN + RESIZE_BORDER;
                    bool bottom = point.Y >= ActualHeight - SHADOW_MARGIN - RESIZE_BORDER;

                    // 返回相应的命中测试结果
                    if (left && top) { handled = true; return (IntPtr)HTTOPLEFT; }      // 左上角
                    if (right && top) { handled = true; return (IntPtr)HTTOPRIGHT; }    // 右上角
                    if (right && bottom) { handled = true; return (IntPtr)HTBOTTOMRIGHT; } // 右下角
                    if (left && bottom) { handled = true; return (IntPtr)HTBOTTOMLEFT; }   // 左下角
                    if (left) { handled = true; return (IntPtr)HTLEFT; }    // 左边框
                    if (right) { handled = true; return (IntPtr)HTRIGHT; }  // 右边框
                    if (top) { handled = true; return (IntPtr)HTTOP; }      // 上边框
                    if (bottom) { handled = true; return (IntPtr)HTBOTTOM; } // 下边框
                    break;

                case WM_GETMINMAXINFO:
                    // 设置窗口的最小尺寸限制
                    if (_minWidth > 0 || _minHeight > 0)
                    {
                        MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));
                        
                        // 计算最小尺寸时需要考虑阴影边距
                        if (_minWidth > 0)
                        {
                            mmi.ptMinTrackSize.x = (int)(_minWidth + SHADOW_MARGIN * 2);
                        }
                        if (_minHeight > 0)
                        {
                            mmi.ptMinTrackSize.y = (int)(_minHeight + SHADOW_MARGIN * 2);
                        }
                        
                        Marshal.StructureToPtr(mmi, lParam, true);
                        handled = true;
                    }
                    break;

                case 0x232: // WM_EXITSIZEMOVE
                    // 结束窗口大小调整或移动操作
                    _isResizing = false;
                    Cursor = Cursors.Arrow;
                    handled = true;
                    break;
            }
            return IntPtr.Zero;
        }

        private void OnWindowMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left && _isDragMove)
            {
                bool canDrag = true;
                
                if (_dragComponent != null)
                {
                    Point clickPoint = e.GetPosition(_dragComponent);
                    canDrag = clickPoint.X >= 0 
                        && clickPoint.X <= _dragComponent.ActualWidth 
                        && clickPoint.Y >= 0 
                        && clickPoint.Y <= _dragComponent.ActualHeight;

                    if (canDrag)
                    {
                        DependencyObject hitTestResult = VisualTreeHelper.HitTest(_dragComponent, clickPoint)?.VisualHit;
                        canDrag = hitTestResult != null && IsAncestorOf(_dragComponent, hitTestResult as DependencyObject);
                    }
                }
                else if (_windowBorder != null)
                {
                    Point clickPoint = e.GetPosition(_windowBorder);
                    canDrag = clickPoint.X >= RESIZE_BORDER 
                        && clickPoint.X <= _windowBorder.ActualWidth - RESIZE_BORDER
                        && clickPoint.Y >= RESIZE_BORDER 
                        && clickPoint.Y <= _windowBorder.ActualHeight - RESIZE_BORDER;
                }

                if (canDrag)
                {
                    DragMove();
                }
            }
        }

        private void OnWindowMouseUp(object sender, MouseButtonEventArgs e)
        {
            _isResizing = false;
        }

        private void DragResize(ResizeDirection direction)
        {
            try 
            {
                HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
                if (hwndSource != null)
                {
                    SendMessage(hwndSource.Handle, 0x112, (IntPtr)(61440 + direction), IntPtr.Zero);
                    
                    // 添加事件处理来监听窗口大小调整完成
                    hwndSource.AddHook(new HwndSourceHook(WndProc));
                }
            }
            catch (Exception)
            {
                _isResizing = false;
            }
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        private enum ResizeDirection
        {
            None = 0,
            Left = 1,
            Right = 2,
            Top = 3,
            TopLeft = 4,
            TopRight = 5,
            Bottom = 6,
            BottomLeft = 7,
            BottomRight = 8,
        }

        /// <summary>
        /// 检查一个视觉对象是否是另一个视觉对象的祖先节点
        /// </summary>
        /// <param name="ancestor">可能的祖先节点</param>
        /// <param name="descendant">可能的后代节点</param>
        /// <returns>如果ancestor是descendant的祖先节点（包括父节点）则返回true，否则返回false</returns>
        private bool IsAncestorOf(DependencyObject ancestor, DependencyObject descendant)
        {
            if (descendant == null) return false;
            
            DependencyObject current = descendant;
            while (current != null)
            {
                if (current == ancestor) return true;
                current = VisualTreeHelper.GetParent(current);
            }
            return false;
        }

        private bool IsWindowSnapped(WINDOWPOS pos, bool checkSize = true)
        {
            double screenLeft = 0;
            double screenTop = 0;
            double screenRight = SystemParameters.WorkArea.Right;
            double screenBottom = SystemParameters.WorkArea.Bottom;
            
            // 检查水平贴边
            bool isSnappedToLeft = Math.Abs(pos.x - screenLeft) <= 1;
            bool isSnappedToRight = Math.Abs(pos.x + pos.cx - screenRight) <= 1;
            bool isHorizontallyHalf = !checkSize || pos.cx >= SystemParameters.WorkArea.Width / 2;
            
            // 检查垂直贴边
            bool isSnappedToTop = Math.Abs(pos.y - screenTop) <= 1;
            bool isSnappedToBottom = Math.Abs(pos.y + pos.cy - screenBottom) <= 1;
            bool isFullHeight = pos.cy >= SystemParameters.WorkArea.Height - 2; // 允许1-2像素的误差
            
            // 更新垂直贴边状态
            _isVerticallySnapped = (isSnappedToTop || isSnappedToBottom) && isFullHeight;
            
            // 返回水平贴边状态
            return (isSnappedToLeft || isSnappedToRight) && isHorizontallyHalf;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct WINDOWPOS
        {
            public IntPtr hwnd;
            public IntPtr hwndInsertAfter;
            public int x;
            public int y;
            public int cx;
            public int cy;
            public uint flags;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct MINMAXINFO
        {
            public POINT ptReserved;
            public POINT ptMaxSize;
            public POINT ptMaxPosition;
            public POINT ptMinTrackSize;
            public POINT ptMaxTrackSize;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct POINT
        {
            public int x;
            public int y;
        }

        /// <summary>
        /// 保存当前窗口的位置和大小
        /// </summary>
        private void SaveWindowPosition()
        {
            if (WindowState == WindowState.Normal)
            {
                _previousWindowRect = new Rect(Left, Top, Width, Height);
            }
        }

        /// <summary>
        /// 窗口最大化
        /// </summary>
        public void Maximize()
        {
            if (WindowState != WindowState.Maximized)
            {
                // 保存当前状态（如果不是从最小化状态来的）
                if (WindowState == WindowState.Normal)
                {
                    SaveWindowPosition();
                }
                WindowState = WindowState.Maximized;
                UpdateWindowMargin();
            }
        }

        /// <summary>
        /// 窗口最小化
        /// </summary>
        public void Minimize()
        {
            if (WindowState != WindowState.Minimized)
            {
                // 如果当前是全屏状态，先保存位置
                if (_isFullScreen)
                {
                    _isFullScreen = false;
                    UpdateWindowMargin();
                }
                WindowState = WindowState.Minimized;
            }
        }

        /// <summary>
        /// 恢复窗口化
        /// </summary>
        public void Restore()
        {
            if (_isFullScreen)
            {
                ToggleFullScreen();
            }
            else if (WindowState != WindowState.Normal)
            {
                WindowState = WindowState.Normal;
                
                // 添加验证确保位置值有效
                if (_previousWindowRect != default && 
                    !double.IsInfinity(_previousWindowRect.Left) && 
                    !double.IsInfinity(_previousWindowRect.Top) && 
                    !double.IsInfinity(_previousWindowRect.Width) && 
                    !double.IsInfinity(_previousWindowRect.Height))
                {
                    Left = _previousWindowRect.Left;
                    Top = _previousWindowRect.Top;
                    Width = _previousWindowRect.Width;
                    Height = _previousWindowRect.Height;
                }
                
                UpdateWindowMargin();
            }
        }

        /// <summary>
        /// 切换最大化/还原状态
        /// </summary>
        public void ToggleMaximize()
        {
            if (_isFullScreen)
            {
                ToggleFullScreen();
                return;
            }

            if (WindowState == WindowState.Maximized)
            {
                Restore();
            }
            else if (WindowState == WindowState.Normal)
            {
                Maximize();
            }
        }

        /// <summary>
        /// 获取当前窗口状态
        /// </summary>
        public WindowStatus CurrentWindowStatus
        {
            get
            {
                if (_isFullScreen) return WindowStatus.FullScreen;
                if (WindowState == WindowState.Maximized)
                    return WindowStatus.Maximized;
                else if (WindowState == WindowState.Minimized)
                    return WindowStatus.Minimized;
                else
                    return WindowStatus.Normal;
            }
        }

        /// <summary>
        /// 切换窗口的全屏/窗口化状态
        /// </summary>
        private void ToggleFullScreen()
        {
            if (!_isFullScreen)
            {
                SaveWindowPosition();
                
                // 保存当前窗口状态
                _previousWindowRect = new Rect(Left, Top, Width, Height);
                
                // 设置全屏
                WindowStyle = WindowStyle.None;
                ResizeMode = ResizeMode.NoResize;
                
                // 获取当前屏幕工作区
                var currentWindow = new WindowInteropHelper(this);
                var screen = SystemParameters.WorkArea;
                
                // 设置窗口位置和大小为全屏
                Left = screen.Left;
                Top = screen.Top;
                Width = screen.Width;
                Height = screen.Height;
                
                _isFullScreen = true;
            }
            else
            {
                // 恢复窗口状态
                WindowStyle = WindowStyle.None;
                ResizeMode = ResizeMode.CanResize;
                
                // 恢复之前保存的窗口位置和大小
                Left = _previousWindowRect.Left;
                Top = _previousWindowRect.Top;
                Width = _previousWindowRect.Width;
                Height = _previousWindowRect.Height;
                
                _isFullScreen = false;
            }
            
            // 更新窗口边距和阴影
            UpdateWindowMargin();
        }

        /// <summary>
        /// 更新窗口背景的透明度
        /// </summary>
        private void UpdateBackgroundOpacity()
        {
            if (_windowBorder == null) return;

            // 如果背景是纯色
            if (_windowBorder.Background is SolidColorBrush solidBrush)
            {
                Color color = solidBrush.Color;
                _windowBorder.Background = new SolidColorBrush(
                    Color.FromArgb(
                        (byte)(_backgroundOpacity * 255),
                        color.R,
                        color.G,
                        color.B
                    )
                );
            }
            // 如果背景是渐变色
            else if (_windowBorder.Background is LinearGradientBrush gradientBrush)
            {
                foreach (GradientStop stop in gradientBrush.GradientStops)
                {
                    Color color = stop.Color;
                    stop.Color = Color.FromArgb(
                        (byte)(_backgroundOpacity * 255),
                        color.R,
                        color.G,
                        color.B
                    );
                }
            }
        }

        /// <summary>
        /// 设置窗口背景颜色（带透明度）
        /// </summary>
        /// <param name="color">背景颜色</param>
        /// <param name="opacity">透明度（可选，默认使用当前透明度）</param>
        public void SetBackgroundColor(Color color, double? opacity = null)
        {
            if (_windowBorder == null) return;

            if (opacity.HasValue)
            {
                BackgroundOpacity = opacity.Value;
            }

            _windowBorder.Background = new SolidColorBrush(
                Color.FromArgb(
                    (byte)(_backgroundOpacity * 255),
                    color.R,
                    color.G,
                    color.B
                )
            );
        }

        /// <summary>
        /// 设置窗口背景渐变色（带透明度）
        /// </summary>
        /// <param name="gradientStops">渐变色停止点集合</param>
        /// <param name="opacity">透明度（可选，默认使用当前透明度）</param>
        /// <param name="angle">渐变角度（可选，默认为0度）</param>
        public void SetBackgroundGradient(GradientStopCollection gradientStops, double? opacity = null, double angle = 0)
        {
            if (_windowBorder == null) return;

            if (opacity.HasValue)
            {
                BackgroundOpacity = opacity.Value;
            }

            var brush = new LinearGradientBrush(gradientStops, angle);
            foreach (GradientStop stop in brush.GradientStops)
            {
                Color color = stop.Color;
                stop.Color = Color.FromArgb(
                    (byte)(_backgroundOpacity * 255),
                    color.R,
                    color.G,
                    color.B
                );
            }
            _windowBorder.Background = brush;
        }
    }

    /// <summary>
    /// 窗口状态枚举
    /// </summary>
    public enum WindowStatus
    {
        /// <summary>
        /// 正常窗口状态
        /// </summary>
        Normal, 
        
        /// <summary>
        /// 最大化状态
        /// </summary>
        Maximized,
        
        /// <summary>
        /// 最小化状态
        /// </summary>
        Minimized,
        
        /// <summary>
        /// 全屏状态
        /// </summary>
        FullScreen
    }
} 